local uci = require("uci")
local util = require("tianku.helpers.util")

local _M = {}
_M.__index = _M

-- 自定义UCI路径
local UCI_PATH = "/usr/lib/lua/tianku/uci"

function _M.new(config_name)
    local self = setmetatable({}, _M)
    self.uci = uci.cursor(UCI_PATH)
    self.config_name = config_name
    self._wheres = {}
    return self
end

-- 获取用户信息
function _M:get(section, option)
    return self.uci:get(self.config_name, section, option)
end

-- 创建用户
function _M:create(data)
    local section = self.uci:add(self.config_name, "user")
    for k, v in pairs(data) do
        self.uci:set(self.config_name, section, k, v)
    end
    self.uci:commit(self.config_name)
    return section
end

-- 更新用户
function _M:update(section, data)
    for k, v in pairs(data) do
        self.uci:set(self.config_name, section, k, v)
    end
    self.uci:commit(self.config_name)
    return true
end

-- 删除用户
function _M:delete(section)
    self.uci:delete(self.config_name, section)
    self.uci:commit(self.config_name)
    return true
end

-- 查询用户列表
function _M:all()
    local users = {}
    self.uci:foreach(self.config_name, "user", function(s)
        table.insert(users, {
            id = s[".name"],
            name = s.name,
            email = s.email,
            status = s.status
        })
    end)
    return users
end

return _M